package com.ruicar.afs.cloud.batch.dayend.process;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.batch.dayend.handle.run.MessageProcessor;
import com.ruicar.afs.cloud.batch.dayend.handle.run.SystemJdbcConfig;
import com.ruicar.afs.cloud.batch.frame.AbsBatchRunner;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.SpringContextHolder;
import com.ruicar.afs.cloud.common.modules.contract.enums.MessageTemplateBusinessEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.PersonRoleTypeEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.RepaymentStatusEnum;
import com.ruicar.afs.cloud.common.modules.contract.enums.YesOrNoEnum;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Description: 短信任务=》接受申请（5050）（合同激活第二天）</p>
 *
 * @author infinity
 * @version 1.0
 * @date 2020/9/18 10:50
 */
@Slf4j
public class AcceptApplicationBathRunner extends AbsBatchRunner {
    private final StringBuffer sqlSms = new StringBuffer(" insert into basic_sms(id,contract_no,channel,code,uid,phone,template_id,estimated_time,sms_content,priority,origin ")
            .append(", dept_id,create_by,create_time ) values(?,?,?,?,?,?,?,?,?,?,? ,?,?,? ) ");
    public static final int TOTAL_NUM = 200;
    //短信
    private final String SHORT_MSG = "short-msg";
    private SystemJdbcConfig systemJdbcConfig= SpringContextHolder.getBean(SystemJdbcConfig.class);
    public void process(String param) {
        Connection base = this.getConnection();
        logger.info("读取==={}", loadBreakPoint());
        Connection contract = this.getConnection(systemJdbcConfig.getBasic());
        Connection contractManage = this.getConnection(systemJdbcConfig.getManage());
        try {
            boolean isFinish = false;
            //获取短信模板信息
            Map map = SpringContextHolder.getBean(MessageProcessor.class).getSms(contractManage, SHORT_MSG, AfsEnumUtil.key(MessageTemplateBusinessEnum.ACCEPT_APPLICATION), AfsEnumUtil.key(YesOrNoEnum.yes));
            while (!isFinish) {
                log.info("处理短信信息--开始");
                String loadBreakPoint = loadBreakPoint();
                logger.info("读取==={}", loadBreakPoint);
                isFinish = acceptApplicationActivation(loadBreakPoint, contract, map);
                log.info("处理短信信息--结束");
            }
            logger.info("读取==={}", loadBreakPoint());
        } catch (Exception e) {
            logger.error("", e);
            throw new AfsBaseException(e.getMessage());
        } finally {
            clean(base);
            clean(contractManage);
            clean(contract);
        }
    }

    /**
     * 接受申请（5050）
     */
    private Boolean acceptApplicationActivation(String loadBreakPoint, Connection contract, Map map) {
        String batchStringDate = batchDateInfo.getBatchStringDate();
        Date batchDate = new Date(batchDateInfo.getBatchDate().getTime());
        Long id = getId(loadBreakPoint);
        StringBuffer sql = new StringBuffer();
        sql.append("select plan.id,plan.contract_no,info.cust_name,info.phone,date_format(main.start_date,'%d') as day,date_format(DATE_SUB(plan.due_date,INTERVAL 1 DAY),'%Y年%m月%d日') as time  ");
        sql.append(" ,FORMAT(plan.receivable_rent,2) as amt,substring(bank.account_no, -4) AS bankNo  ");
        sql.append(" from  basic_main_info main INNER JOIN  basic_repayment_plan plan  on main.contract_no  =plan.contract_no  ");
        sql.append(" inner join basic_contract_cust_relation relation  on relation.contract_no = plan.contract_no and relation.cust_role=?  ");
        sql.append(" inner join basic_bank_card bank  on bank.contract_no = plan.contract_no  and bank.ver_status ='alreadySign' ");
        sql.append(" inner join basic_cust_base_info info on info.cust_no = relation.cust_no ");
        sql.append(" where plan.term_no=1  and  plan.receivable_rent =0  and date_format(DATE_ADD(main.start_date,INTERVAL 1 DAY),'%Y%m%d')  =?   and plan.status=? ");
        if (id != null) {
            sql.append(" and plan.id> ? ");
        }
        sql.append(" order by plan.id asc  limit 0, ? ");

        PreparedStatement ps = null;
        ResultSet rs = null;
        PreparedStatement psSms=null;
        try {
            ps = contract.prepareStatement(sql.toString());
            psSms = contract.prepareStatement(sqlSms.toString());
            ps.setString(1, AfsEnumUtil.key(PersonRoleTypeEnum.MAIN_PERSON));
            ps.setString(2, batchStringDate);
            ps.setString(3, AfsEnumUtil.key(RepaymentStatusEnum.UNPAID));
            if (id != null) {
                ps.setLong(4, id);
                ps.setInt(5, TOTAL_NUM);
            } else {
                ps.setLong(4, TOTAL_NUM);
            }
            rs = ps.executeQuery();
            String phone = null;
            String contractNo = null;
            String name = null;
            Map valueMap = new HashMap();
            int i=0;
            while (rs != null && rs.next()) {
                contractNo = rs.getString("contract_no");
                name = rs.getString("cust_name");
                phone = rs.getString("phone");
                id = rs.getLong("id");
                valueMap.put("day", rs.getString("day"));
                valueMap.put("time", rs.getString("time"));
                valueMap.put("amt", rs.getString("amt"));
                valueMap.put("bankNo", rs.getString("bankNo"));
                i++;
              SpringContextHolder.getBean(MessageProcessor.class).saveSms(psSms,map, phone, contractNo, name, valueMap,batchDate);
            }
            //短信已发送完毕
            if (i==0) {
                return Boolean.TRUE;
            }
            psSms.executeBatch();
            contract.commit();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("startId", id);
            saveBreakPoint(jsonObject.toString());
            return Boolean.FALSE;
        } catch (SQLException e) {
            logger.error("", e);
            throw new AfsBaseException(e.getMessage());
        } finally {
            clean(ps);
            clean(rs);
        }
    }

    //获取断点id
    private Long getId(String loadBreakPoint) {
        if (StringUtil.isBlank(loadBreakPoint)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(loadBreakPoint);
        Long startId = (Long) jsonObject.get("startId");
        return startId;
    }

}
